package com.bs.visitservice.common;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 处理商家端websocket连接信息
 */
public class MessageHandler extends TextWebSocketHandler {
    public static final Map<WebSocketSession,Long> SESSION_MAP = new ConcurrentHashMap<WebSocketSession, Long>();
    public static final Map<Long,WebSocketSession> LOGIN_NO_SESSIONID = new ConcurrentHashMap<>();
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Long loginNo = SESSION_MAP.get(session);
        if(loginNo == null){
            System.out.println(session.getId());
            return;
        }
        System.out.println("sessionId"+session.getId()+"断开连接;no:"+loginNo);
        SESSION_MAP.remove(session);
        LOGIN_NO_SESSIONID.remove(loginNo);
        session.close();
        System.out.println("sesson is close....");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String param  = message.getPayload();
        if(param!=null && !"".equals(param)){
            if(SESSION_MAP.containsKey(session)){
                SimpleDateFormat dataFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String date = dataFormatter.format(new Date());
                System.out.println(date + session.getId()+" : Received client heartbeat......");
                return;
            }

            System.out.println("classId"+this+",sessionId"+session.getId()+"连接;no:"+param);
            Long loginNo = Long.valueOf(param);
            LOGIN_NO_SESSIONID.put(loginNo,session);
            SESSION_MAP.put(session,loginNo);
        }
    }
}
